/*
 * Copyright (c) 2011-2024, Cpjit (cpjit@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cpjit.data;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.cpjit.data.annotation.Immutable;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.util.ReflectionUtils;

import java.sql.SQLException;
import java.util.Map;

/**
 * @author yonghuan[cpjit@qq.com]
 * @see AuditingInnerInterceptor
 * @see Immutable
 */
@Slf4j
public class ImmutableInnerInterceptor implements InnerInterceptor {

    private void beforeUpdateInternal(MappedStatement ms, Object entity) {
        ReflectionUtils.doWithFields(entity.getClass(), field -> {
            ReflectionUtils.makeAccessible(field);
            Object value = ReflectionUtils.getField(field, entity);
            if (value == null) {
                return;
            }
            if (field.getAnnotation(Immutable.class) != null) {
                log.warn("试图修改不可变的字段{}#{}，将自动设置字段值为null", field.getDeclaringClass().getName(), field.getName());
                ReflectionUtils.setField(field, entity, null);
            }
        });
    }

    private void beforeUpdateInternal(MappedStatement ms, LambdaUpdateWrapper ew) {

    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        if (ms.getSqlCommandType() != SqlCommandType.UPDATE) {
            return;
        }
        Object entity = null;
        LambdaUpdateWrapper updateWrapper = null;
        if (parameter instanceof Map) {
            // 取到实体类
            Map<String, Object> map = (Map<String, Object>) parameter;
            if (map.containsKey(Constants.ENTITY)) {
                entity = ((Map<String, Object>) parameter).get(Constants.ENTITY);
            }
            final Object ew = map.getOrDefault(Constants.WRAPPER, null);
            if (ew instanceof LambdaUpdateWrapper<?> lambdaUpdateWrapper) {
                updateWrapper = lambdaUpdateWrapper;
            }
        } else {
            entity = parameter;
        }
        if (entity != null && TableInfoHelper.getTableInfo(entity.getClass()) == null) {
            entity = null;
        }
        if (entity != null) {
            beforeUpdateInternal(ms, entity);
        }
        // 针对LambdaUpdateWrapper的处理
        if (updateWrapper != null) {
            beforeUpdateInternal(ms, updateWrapper);
        }
    }
}
